const cloudHelper = require('../../../config/project_helpers_config').cloudHelper;
const pageHelper = require('../../../config/project_helpers_config').pageHelper;
const ProjectFeedbackBiz = require('../../../config/path_resolver.js').pageHelper;
const ProjectFeedbackHelper = require('../../../config/path_resolver.js').pageHelper;
const validate = require('../../../config/path_resolver.js').pageHelper;

// 使用统一配置入口导入createStoreBindings
const npmConfig = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('npm_config.js');
const { createStoreBindings } = npmConfig;

const { feedbackStore } = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('store_config.js');

Page({
    data: {
        title: '',
        isLoad: false,
        id: '',
        formType: 'add', // add 为添加，edit 为编辑
        
        projectId: '',
        projectName: '',
        customerId: '',
        customerName: '',
        
        formTitle: '',
        formContent: '',
        formType: 1,
        formPriority: 2,
        formImages: [],
        formFiles: [],
        
        typeOptions: ProjectFeedbackHelper.TYPE_OPTIONS,
        priorityOptions: ProjectFeedbackHelper.PRIORITY_OPTIONS
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 创建MobX绑定
        this.storeBindings = createStoreBindings(this, {
            store: feedbackStore,
            fields: [
                'currentFeedback',
                'loading'
            ],
            actions: [
                'addFeedback',
                'updateFeedback',
                'setCurrentFeedback',
                'setLoading'
            ]
        });
        
        if (options && options.id) {
            this.setData({
                id: options.id,
                formType: 'edit',
                title: '编辑反馈'
            });
            this._loadDetail(options.id);
        } else {
            this.setData({
                formType: 'add',
                title: '填写反馈单',
                isLoad: true,
                formImages: [],
                formFiles: [],
                formTitle: '',
                formContent: '',
                formType: 1,
                formPriority: 2,
            });
            
            if (options && options.projectId) {
                this.setData({
                    projectId: options.projectId
                });
                
                if (options.projectName) {
                    this.setData({
                        projectName: options.projectName
                    });
                } else {
                    this._loadProjectDetail(options.projectId);
                }
            }
            
            if (options && options.customerId) {
                this.setData({
                    customerId: options.customerId
                });
                
                if (options.customerName) {
                    this.setData({
                        customerName: options.customerName
                    });
                } else {
                    this._loadCustomerDetail(options.customerId);
                }
            }
        }
    },
    
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        // 销毁MobX绑定
        this.storeBindings.destroyStoreBindings();
    },
    
    /**
     * 加载项目详情
     */
    _loadProjectDetail: async function(projectId) {
        try {
            this.setLoading(true);
            
            let params = {
                id: projectId
            };
            let opt = {
                title: '加载中'
            };
            let project = await cloudHelper.callCloudData('research_project/detail', params, opt);
            if (project) {
                this.setData({
                    projectName: project.PROJECT_NAME
                });
            }
        } catch (err) {
            console.error(err);
        } finally {
            this.setLoading(false);
        }
    },
    
    /**
     * 加载客户详情
     */
    _loadCustomerDetail: async function(customerId) {
        try {
            this.setLoading(true);
            
            let params = {
                id: customerId
            };
            let opt = {
                title: '加载中'
            };
            let customer = await cloudHelper.callCloudData('customer/detail', params, opt);
            if (customer) {
                this.setData({
                    customerName: customer.CUSTOMER_NAME
                });
            }
        } catch (err) {
            console.error(err);
        } finally {
            this.setLoading(false);
        }
    },
    
    /**
     * 加载反馈详情
     */
    _loadDetail: async function(id) {
        try {
            this.setLoading(true);
            
            let params = {
                id
            };
            let opt = {
                title: '加载中'
            };
            let feedback = await cloudHelper.callCloudData('feedback/detail', params, opt);
            if (!feedback) {
                this.setData({
                    isLoad: true
                });
                return;
            }
            
            // 设置当前反馈到MobX
            this.setCurrentFeedback(feedback);
            
            // 处理文件大小格式化
            let files = feedback.FEEDBACK_FILES || [];
            files.forEach(file => {
                if (!file.sizeKB && file.size) {
                    file.sizeKB = (file.size / 1024).toFixed(1);
                }
            });
            
            // 页面本地数据同步
            this.setData({
                isLoad: true,
                projectId: feedback.FEEDBACK_PROJECT_ID,
                projectName: feedback.PROJECT_NAME || '',
                customerId: feedback.FEEDBACK_CUSTOMER_ID,
                customerName: feedback.FEEDBACK_CUSTOMER_NAME || '',
                formTitle: feedback.FEEDBACK_TITLE,
                formContent: feedback.FEEDBACK_CONTENT,
                formType: feedback.FEEDBACK_TYPE,
                formPriority: feedback.FEEDBACK_PRIORITY,
                formImages: feedback.FEEDBACK_IMAGES || [],
                formFiles: files
            });
        } catch (err) {
            console.error(err);
        } finally {
            this.setLoading(false);
        }
    },
    
    /**
     * 表单数据保存
     */
    bindFormSubmit: async function() {
        // 数据校验
        let data = this.data;
        
        if (!data.projectId) {
            return pageHelper.showModal('请选择项目');
        }
        
        if (!data.formTitle) {
            return pageHelper.showModal('请填写反馈标题');
        }
        
        if (!data.formContent) {
            return pageHelper.showModal('请填写反馈内容');
        }
        
        let params = {
            projectId: data.projectId,
            title: data.formTitle,
            content: data.formContent,
            type: data.formType,
            priority: data.formPriority,
            customerId: data.customerId,
            customerName: data.customerName,
            images: data.formImages,
            files: data.formFiles
        };
        
        try {
            this.setLoading(true);
            
            let result;
            if (this.data.formType === 'edit') {
                // 编辑模式
                params.id = this.data.id;
                result = await cloudHelper.callCloudSumbit('feedback/update', params);
                
                // 更新MobX中的数据
                this.updateFeedback(this.data.id, params);
                
                pageHelper.showSuccToast('编辑成功', 1500);
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            } else {
                // 添加模式
                result = await cloudHelper.callCloudSumbit('feedback/add', params);
                
                // 更新MobX中的数据
                const newId = result.data.id;
                
                pageHelper.showSuccToast('提交成功', 1500);
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            }
        } catch (err) {
            console.error(err);
        } finally {
            this.setLoading(false);
        }
    },
    
    /**
     * 选择项目
     */
    bindSelectProject: function() {
        wx.navigateTo({
            url: '/pages/project/selector/project_selector?callback=onProjectSelect'
        });
    },
    
    /**
     * 项目选择回调
     */
    onProjectSelect: function(e) {
        if (e && e.detail && e.detail.id) {
            this.setData({
                projectId: e.detail.id,
                projectName: e.detail.name || ''
            });
        }
    },
    
    /**
     * 选择客户
     */
    bindSelectCustomer: function() {
        wx.navigateTo({
            url: '/pages/customer/selector/customer_selector?callback=onCustomerSelect'
        });
    },
    
    /**
     * 客户选择回调
     */
    onCustomerSelect: function(e) {
        if (e && e.detail && e.detail.id) {
            this.setData({
                customerId: e.detail.id,
                customerName: e.detail.name || ''
            });
        }
    },
    
    /**
     * 表单数据变更
     */
    bindFormDataChange: function(e) {
        let field = e.currentTarget.dataset.field;
        let val = e.detail.value;
        
        switch (field) {
            case 'Title':
                this.setData({ formTitle: val });
                break;
            case 'Content':
                this.setData({ formContent: val });
                break;
            case 'Type':
                this.setData({ formType: parseInt(val) + 1 });
                break;
            case 'Priority':
                this.setData({ formPriority: parseInt(val) + 1 });
                break;
        }
    },
    
    /**
     * 选择图片
     */
    bindChooseImage: function() {
        let that = this;
        wx.chooseImage({
            count: 9 - that.data.formImages.length,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: async function(res) {
                let imgList = [];
                for (let i = 0; i < res.tempFilePaths.length; i++) {
                    let path = res.tempFilePaths[i];
                    
                    // 上传图片到云存储
                    let cloudPath = ProjectFeedbackBiz.getImageCloudPath(path, that.data.projectId);
                    let result = await cloudHelper.transTempFileToCloud(path, cloudPath);
                    
                    imgList.push(result.fileID);
                }
                
                // 拼接之前的图片列表
                let oldList = that.data.formImages;
                let newList = oldList.concat(imgList);
                
                that.setData({
                    formImages: newList
                });
            }
        });
    },
    
    /**
     * 删除图片
     */
    bindDelImage: function(e) {
        let idx = e.currentTarget.dataset.idx;
        let imgList = this.data.formImages;
        imgList.splice(idx, 1);
        this.setData({
            formImages: imgList
        });
    },
    
    /**
     * 预览图片
     */
    bindPreviewImage: function(e) {
        let url = e.currentTarget.dataset.url;
        wx.previewImage({
            urls: this.data.formImages,
            current: url
        });
    },
    
    /**
     * 选择文件
     */
    bindChooseFile: function() {
        let that = this;
        wx.chooseMessageFile({
            count: 5 - that.data.formFiles.length,
            type: 'file',
            success: async function(res) {
                let fileList = [];
                for (let i = 0; i < res.tempFiles.length; i++) {
                    let file = res.tempFiles[i];
                    
                    // 上传文件到云存储
                    let cloudPath = ProjectFeedbackBiz.getFileCloudPath(file.name, that.data.projectId);
                    let result = await cloudHelper.transTempFileToCloud(file.path, cloudPath);
                    
                    // 计算并格式化文件大小
                    let fileSize = file.size;
                    let fileSizeKB = (fileSize / 1024).toFixed(1);
                    
                    fileList.push({
                        name: file.name,
                        size: file.size,
                        sizeKB: fileSizeKB, // 添加格式化后的文件大小
                        url: result.fileID
                    });
                }
                
                // 拼接之前的文件列表
                let oldList = that.data.formFiles;
                let newList = oldList.concat(fileList);
                
                that.setData({
                    formFiles: newList
                });
            }
        });
    },
    
    /**
     * 删除文件
     */
    bindDelFile: function(e) {
        let idx = e.currentTarget.dataset.idx;
        let fileList = this.data.formFiles;
        fileList.splice(idx, 1);
        this.setData({
            formFiles: fileList
        });
    },
    
    /**
     * 打开文件
     */
    bindOpenFile: function(e) {
        let url = e.currentTarget.dataset.url;
        wx.showLoading({
            title: '文件打开中...',
        });
        
        wx.cloud.downloadFile({
            fileID: url,
            success: res => {
                wx.hideLoading();
                wx.openDocument({
                    filePath: res.tempFilePath,
                    showMenu: true
                });
            },
            fail: err => {
                wx.hideLoading();
                console.error(err);
                pageHelper.showModal('文件打开失败，请重试');
            }
        });
    }
}); 